/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-05-15     
 */
package com.task.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.task.utils.FileUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.google.common.collect.Lists;
import com.task.bean.Constants;
import com.task.bean.EnumConstants.ChildTaskStatus;
import com.task.bean.EnumConstants.ParentTaskStatus;
import com.task.bean.ParentTaskBean;
import com.task.entity.ChildTask;
import com.task.entity.FinishTasks;
import com.task.entity.ParentTask;
import com.task.entity.Store;
import com.task.service.IChildTaskService;
import com.task.service.IFinishTasksService;
import com.task.service.IParentTaskService;
import com.task.service.ISystemService;
import com.task.utils.DownloadImageUtil;
import com.task.utils.TaskDomain;

import net.sf.json.JSONObject;

/**
 * 手机页面-任务控制器
 */
@Controller
public class TaskPlatformController {

	private static final Logger LOGGER = LoggerFactory.getLogger(TaskPlatformController.class);

	@Autowired
	IParentTaskService parentTaskService;

	@Autowired
	IChildTaskService childTaskService;

	@Autowired
	ISystemService systemService;

	@Autowired
	IFinishTasksService finishTasksService;

	@Autowired
	com.task.service.IWxService wxService;

	/**
	 * <查询子任务列表[前二十条]>
	 * 
	 * @param offset
	 * @param limit
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/findChildTaskList.json")
	public JSONObject findChildTaskList(
			@RequestParam(value = "orderDirection", defaultValue = Constants.DESC) String orderDirection,
			@RequestParam(value = "orderField", defaultValue = Constants.ID) String orderField,
			@RequestParam(value = "offset", defaultValue = Constants.DEFAULT_PAGE) int offset,
			@RequestParam(value = "limit", defaultValue = Constants.DEFAULT_ROWS) int limit, ServletRequest request) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(Constants.ROWS, new ArrayList<ParentTaskBean>());
		jsonObject.put(Constants.TOTAL, 0);
		try {
			int pageNum = offset / limit + 1;
			Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
			// 子任务 没有创建时间,所以根据 Id倒序排列

			// 查询条件 状态 - [发布中]的子任务
			searchParams.put("EQ_status", ChildTaskStatus.PUBLISH);
			Page<ChildTask> page = childTaskService.findChildList(searchParams, pageNum, limit, orderDirection,
					orderField);
			if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
				List<TaskDomain> taskList = new ArrayList<TaskDomain>();

				for (ChildTask child : page.getContent()) {
					TaskDomain domain = new TaskDomain();
					ParentTask pt = parentTaskService.findById(child.getParentTaskId());
					if (null != pt) {
						domain.setTaskName(pt.getTaskName());
						domain.setEndDate(pt.getEndTime());
						domain.setStartDate(pt.getStartTime());
					}
					domain.setId(child.getId().toString());
					domain.setStoreAddress(child.getStore().getStoreAddress());
					domain.setStoreCode(child.getStoreCode());
					domain.setStoreName(child.getStore().getStoreName());
					domain.setCode(child.getCode());
					taskList.add(domain);
				}
				jsonObject.put(Constants.ROWS, taskList);
				jsonObject.put(Constants.TOTAL, page.getTotalElements());
			}
		} catch (Exception e) {
			LOGGER.error("find parentTask page error:{}", e);
		}
		return jsonObject;
	}

	/**
	 * <转到任务详情页面<子任务>>
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/subTaskDetail.html")
	public String subTaskDetail(ModelMap model, @RequestParam(value = "userId") String userId,
			@RequestParam(value = "id", required = false) Long id) {
		ChildTask ct = childTaskService.findById(id);
		ParentTask pt = ct.getParentTask();
		if (pt.getReward() != null) {
			pt.setRewardName("¥" + pt.getReward());
		} else {
			pt.setRewardName(Constants.FREE);
		}
		Store store = ct.getStore();
		if (StringUtils.isNotBlank(pt.getTaskGuidancePictures())) {
			String pics = pt.getTaskGuidancePictures();
			String[] picArr = StringUtils.split(pics, ",");
			List<String> imagesList = Lists.newArrayList();
			for (String pic : picArr) {
				imagesList.add(pic);
			}
			pt.setImagesList(imagesList);
		}
		if (pt.getTaskType() != null) {
			pt.setTaskTypaName(pt.getTaskType().getMsg());
		}
		model.addAttribute("pt", pt);
		model.addAttribute("ct", ct);
		model.addAttribute("store", store);
		model.addAttribute("taskType", pt.getTaskType().getMsg());
		if (userId.equals(ct.getUserId()) || StringUtils.isBlank(ct.getUserId())) {
			if (ct.getStatus().equals(ChildTaskStatus.PUBLISH)) {
				model.addAttribute("status", 0);
			} else if (ct.getStatus().equals(ChildTaskStatus.DOING)) {
				model.addAttribute("status", 2);
			}
		} else {
			model.addAttribute("status", 1);
		}
		model.addAttribute("userId", userId);
		model.addAttribute("id", id);
		return "/mobile/taskDetails";
	}

	/**
	 * <转到任务详情页面<子任务>>
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/taskStart.html")
	public String subSaskStart(ModelMap model, @RequestParam(value = "userId") String userId,
			@RequestParam(value = "id") Long id) {
		ChildTask ct = childTaskService.findById(id);
		FinishTasks ft = finishTasksService.findByChildTaskId(id);
		ParentTask pt = ct.getParentTask();
		Store store = ct.getStore();
		if (StringUtils.isNotBlank(pt.getTaskGuidancePictures())) {
			String pics = pt.getTaskGuidancePictures();
			String[] picArr = StringUtils.split(pics, ",");
			List<String> imagesList = Lists.newArrayList();
			for (String pic : picArr) {
				imagesList.add(pic);
			}
			pt.setImagesList(imagesList);
		}

		if (null != ft && StringUtils.isNotBlank(ft.getImagesUrl())) {
			String pics = ft.getImagesUrl();
			String[] picArr = StringUtils.split(pics, ",");
			List<String> imagesList = Lists.newArrayList();
			for (String pic : picArr) {
				imagesList.add(pic);
			}
			ft.setImagesList(imagesList);
		}
		if (pt.getTaskType() != null) {
			pt.setTaskTypaName(pt.getTaskType().getMsg());
		}
		model.addAttribute("pt", pt);
		model.addAttribute("ct", ct);
		model.addAttribute("ft", ft);
		model.addAttribute("store", store);
		model.addAttribute("taskType", pt.getTaskType().getMsg());
		model.addAttribute("userId", userId);
		model.addAttribute("id", id);
		return "/mobile/taskStart";
	}

	/**
	 * <更新子任务状态>
	 * 
	 * @param
	 * @return
	 * @see [更新完成跳转至任务执行页面]
	 */
	@RequestMapping(value = "/pickUpTask.json")
	public String pickUpTask(@RequestParam(value = "id", required = true) Long id, ModelMap model) {
		try {
			childTaskService.updateStatus(ChildTaskStatus.DOING, id);

			ChildTask child = childTaskService.findById(id);
			if (null != child) {
				ParentTask pt = child.getParentTask();
				if (null != pt) {
					model.addAttribute("parent", pt);
					model.addAttribute("taskType", pt.getTaskType().getMsg());
				}
			}
			model.addAttribute("child", child);
			model.addAttribute("status", child.getStatus().getMsg());
		} catch (Exception e) {
			LOGGER.error("pickUpTask error {}", e);
		}
		return "redirect:/mobile.html";
	}

	/**
	 * <更新子任务状态>
	 * 
	 * @param parentTask
	 * @return
	 * @see [更新完成跳转至相应页面]
	 */
	@RequestMapping(value = "/updateStatus.json")
	public String updateStatus(@RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "status", defaultValue = "0") Integer status,
			@RequestParam(value = "location") String location, @RequestParam(value = "latitude") Float latitude,
			@RequestParam(value = "longitude") Float longitude, ModelMap model) {
		try {
			ChildTask child = childTaskService.findById(id);
			if (status == 0) {
				// 抢单 + 抢单时间 
				if (StringUtils.isBlank(child.getUserId())) {
					child.setPickUpTime(new Date());
					child.setStatus(ChildTaskStatus.DOING);
					child.setUserId(userId);
					ParentTask p = parentTaskService.findById(child.getParentTaskId());
					if (null != p && !ParentTaskStatus.DOING.equals(p.getStatus())) {
						p.setStatus(ParentTaskStatus.DOING);
						parentTaskService.save(p);
					}
				}
			} else if (status == 1) {
				// 放弃
				child.setStatus(ChildTaskStatus.PUBLISH);
				child.setPickUpTime(null);
				child.setPickAddress(null);
				child.setLatitude(null);
				child.setLongitude(null);
				child.setUserId(null);
			} else {
				// 执行
				child.setPickAddress(location);
				child.setLatitude(latitude);
				child.setLongitude(longitude);
				child.setStatus(ChildTaskStatus.DOING);
			}
			childTaskService.update(child);

			if (null != child) {
				ParentTask pt = child.getParentTask();
				if (null != pt) {
					model.addAttribute("parent", pt);
					model.addAttribute("taskType", pt.getTaskType().getMsg());
				}
			}
			model.addAttribute("child", child);
			model.addAttribute("userId", userId);
			model.addAttribute("id", id);
			model.addAttribute("status", child.getStatus().getMsg());
		} catch (Exception e) {
			LOGGER.error("updateStatus error {}", e);
		}
		if (status == 0) {
			// 跳转至 任务执行页面
			return "redirect:/subTaskDetail.html";
		} else if (status == 1) {
			// 跳转至 我的任务
			return "redirect:/mobile.html";
		} else {
			// 跳转至任务[执行 -提交]页面
			return "redirect:/taskStart.html";
		}
	}

	/**
	 * <提交子任务>
	 * 
	 * @param parentTask
	 * @return
	 * @see [更新完成跳转至相应页面]
	 */
	@RequestMapping(value = "/submitTask.json")
	public String submitTask(@RequestParam(value = "id", required = true) Long id,
			@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "taskDesc", required = false) String taskDesc,
			@RequestParam(value = "imageUrl", required = false) String imageUrl,
			@RequestParam(value = "status", defaultValue = "0") Integer status, ModelMap model,
			HttpServletRequest request) {
		try {
			String fileUploadRootPath = FileUtils.getContextRootPath(request);
			if (!fileUploadRootPath.endsWith(File.separator)) {
				fileUploadRootPath = fileUploadRootPath + File.separator;
			}
			String absolutePath = fileUploadRootPath + Constants.IMAGE_DIR;
			File dir = new File(absolutePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			model.addAttribute("id", id);
			model.addAttribute("userId", userId);
			if (status == 0) {
				// 跳转至 任务执行页面
				return "redirect:/subTaskDetail.html";
			} else if (status == 1) {
				String accessToken = wxService.saveAndGetAccessToken();
				finishTasksService.submitTask(id, userId, imageUrl, accessToken, taskDesc, absolutePath);

				// 提交任务
				/*
				 * childTaskStatus = ChildTaskStatus.SUBMIT; ChildTask task =
				 * childTaskService.findById(id); FinishTasks finishTask = new
				 * FinishTasks(); finishTask.setChildTaskId(id);
				 * finishTask.setFinishTime(new Date());
				 * finishTask.setUserId(userId); StringBuffer sb = new
				 * StringBuffer();
				 * 
				 * if (StringUtils.isNotBlank(imageUrl)) { String[] images =
				 * imageUrl.split(","); for (String image : images) { String
				 * fileUrl = DownloadImageUtil.downloadMedia(accessToken, image,
				 * url, absolutePath); if (StringUtils.isNotBlank(fileUrl)) {
				 * fileUrl = File.separator + fileUrl;
				 * sb.append(fileUrl).append(","); } }
				 * System.out.println(sb.toString()); if (sb.length() > 0)
				 * finishTask.setImagesUrl(sb.substring(0, sb.length() - 1)); }
				 * finishTask.setTaskDesc(taskDesc); // 保存完成任务信息
				 * finishTasksService.save(finishTask); task.setFinishTime(new
				 * Date()); task.setUserId(userId);
				 * task.setStatus(childTaskStatus); // 更新子任务状态
				 * childTaskService.update(task);
				 */
				return "redirect:/myTask.html?userId=" + userId;
			}
		} catch (Exception e) {
			LOGGER.error("updateStatus error {}", e);
		}
		return "redirect:/myTask.html?userId=" + userId;
	}

	/**
	 * <查询我的任务列表[前二十条]>
	 * 
	 * @param offset
	 * @param limit
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/findMyTaskList.json")
	public JSONObject findMyTaskList(@RequestParam(value = "status", defaultValue = "DOING") String status,
			@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "orderDirection", defaultValue = Constants.DESC) String orderDirection,
			@RequestParam(value = "orderField", defaultValue = Constants.ID) String orderField,
			@RequestParam(value = "offset", defaultValue = Constants.DEFAULT_PAGE) int offset,
			@RequestParam(value = "limit", defaultValue = "10") int limit, ServletRequest request) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(Constants.ROWS, new ArrayList<ParentTaskBean>());
		jsonObject.put(Constants.TOTAL, 0);
		try {
			int pageNum = (offset + 1) > 1 ? offset+1 : 1;
			  limit = offset ==0 ? 10 :1;
			Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
			// 子任务 没有创建时间,所以根据 Id倒序排列
			searchParams.put("EQ_userId", userId);
			// 查询条件 状态
			if (status.equals("DOING")) {
				searchParams.put("EQ_status", ChildTaskStatus.DOING);
				orderField = "pickUpTime";
				orderDirection = "asc";
			} else if (status.equals("SUBMIT")) {
				searchParams.put("EQ_status", ChildTaskStatus.SUBMIT);
				orderField = "finishTime";
				orderDirection = "asc";
			} else {
				searchParams.put("EQ_status", ChildTaskStatus.PASS);
				List<ChildTask> ctList1 = childTaskService.findByCondition(searchParams);
				searchParams.put("EQ_status", ChildTaskStatus.NOPASS);
				List<ChildTask> ctList2 = childTaskService.findByCondition(searchParams);
				ctList2.addAll(ctList1);
				searchParams.remove("EQ_status");
				StringBuffer sb = new StringBuffer();
				String codes = "";
				for (ChildTask ct : ctList2) {
					sb.append(ct.getCode()).append(",");
				}
				if (sb.length() > 0) {
					codes = sb.substring(0, sb.length() - 1);
				}
				searchParams.put("IN_code", codes);
				orderField = "finishTime";
				orderDirection = "asc";
			}
			Page<ChildTask> page = childTaskService.findMyTaskList(searchParams, pageNum, limit, orderDirection,
					orderField);
			if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
				List<TaskDomain> taskList = new ArrayList<TaskDomain>();

				for (ChildTask child : page.getContent()) {
					TaskDomain domain = new TaskDomain();
					ParentTask pt = parentTaskService.findById(child.getParentTaskId());
					if (null != pt) {
						domain.setTaskName(pt.getTaskName());
						domain.setEndDate(pt.getEndTime());
						domain.setStartDate(pt.getStartTime());
						domain.setTaskType(pt.getTaskType().getMsg());
					}
					domain.setId(child.getId().toString());
					domain.setStatus(child.getStatus().toString());
					domain.setStoreAddress(child.getStore().getStoreAddress());
					domain.setStoreCode(child.getStoreCode());
					domain.setStoreName(child.getStore().getStoreName());
					domain.setCode(child.getCode());
					if (child.getReward() != null) {
						domain.setMoney("¥" + child.getReward());
					} else {
						domain.setMoney(Constants.FREE);
					}
					taskList.add(domain);
				}
				jsonObject.put(Constants.ROWS, taskList);
				jsonObject.put(Constants.TOTAL, page.getTotalElements());
			}
		} catch (Exception e) {
			LOGGER.error("  findMyTaskList page error:{}", e);
		}
		return jsonObject;
	}

	/**
	 * <转到我的任务列表>
	 * 
	 * @param model
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/myTask.html")
	public String myTask(ModelMap model, @RequestParam(value = "userId") String userId) {
		model.addAttribute("userId", userId);
		return "/mobile/myTask";
	}

}